package tcp

import (
	"net"
	"fmt"
)

var Ip string

func Server() {
	lis, err := net.Listen("tcp", Ip)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer lis.Close()
	for {
		conn, err := lis.Accept()
		if err != nil {
			fmt.Println("建立连接错误:%v\n", err)
			continue
		}
		fmt.Println(conn.RemoteAddr(), conn.LocalAddr())
		go handle(conn)
	}
}

func handle(conn net.Conn) {
	defer conn.Close()
	for {
		var buf = make([]byte,10)
		inputN,err := conn.Read(buf)
		if err != nil{
			fmt.Println("conn read error:",err)
			return
		}
		// sprintf 返回一个格式化字符串,而不输出
		output := fmt.Sprintf("read %d bytes,content is %s\n",inputN,string(buf))
		conn.Write([]byte(output))
	}
}